﻿namespace Vboot.Core.Module.Sys;

[ApiDescriptionSettings("Sys", Tag = "门户管理-菜单")]
public class SysPortalMenuApi : IDynamicApiController
{
    private readonly SysPortalMenuService _service;

    public SysPortalMenuApi(
        SysPortalMenuService service)
    {
        _service = service;
    }

    [QueryParameters]
    public async Task<dynamic> GetTree(string porid,string name)
    {
        //select id,pid,name,type,crtim,uptim,notes,comp,shtag,path from sys_portal_menu where porid=@porid order by ornum
        var treeList = await _service.repo.Context
            .Queryable<SysPortalMenu>()
            .Where(t=>t.porid==porid)
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .OrderBy(it=>it.ornum)
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }

    public async Task<SysPortalMenu> GetOne(string id)
    {
        var menu = await _service.SingleAsync(id);
        if (menu.pid != null)
        {
            menu.pname = await _service.repo.Context.Queryable<SysPortalMenu>()
                .Where(it => it.id == menu.pid).Select(it => it.name).SingleAsync();
        }
        return menu;
    }

    public async Task Post(SysPortalMenu menu)
    {
        menu.id = YitIdHelper.NextId() + "";
        await _service.InsertAsync(menu);
        await PostFlush();
    }

    public async Task Put(SysPortalMenu menu)
    {
        await _service.UpdateAsync(menu);
        await PostFlush();
    }

    public async Task Delete(string ids)
    {
        var idArr = ids.Split(",");
        foreach (var id in idArr)
        {
            var count = await
                _service.repo.Context.Queryable<SysPortalMenu>().Where(it => it.pid == id).CountAsync();
            if (count > 0)
            {
                throw new Exception("有子菜单或按钮无法删除");
            }
        }

        await _service.DeleteAsync(ids);
        await PostFlush();
    }
    
    [NonAction]
    private async Task PostFlush()
    {
        await _service.repo.Context.Updateable<SysOrgUser>().SetColumns(it => it.catag == false)
            .Where(it => it.catag == true)
            .ExecuteCommandAsync();
        
        await _service.repo.Context.Updateable<SysCoopUser>().SetColumns(it => it.catag == false)
            .Where(it => it.catag == true)
            .ExecuteCommandAsync();
    }
}